import dayjs from "dayjs";
import useHotelStore from "@/store/hotel";
import {Logger} from "sass";

export function useMixin() {

    interface ProviderDetailEvent {
        type: number;
        id: string;
        name : string;
    }

    const hotelStore = useHotelStore();

    const pageBack = (currentPageNumber:number) => {
        if (Number(currentPageNumber) > 1) {
            uni.navigateBack();
        } else {
            uni.reLaunch({
                url: '/pages/index/index',
            });
        }
    };

    const distanceTransform = (distance:string | number) => {
        return (Number(distance) / 1000).toFixed(2);
    };

    const providerStatus = (status:string | number) => {
        switch (Number(status)) {
            case 0:
                return "营业中";
            case 2:
                return "暂停营业";
        }
    };

    const transferIdCardType = (idType :number) => {
        /*身份证(1,"身份证"),
            永居证(2,"永居证"),
            台胞证(3,"台胞证"),
            护照(4,"护照"),
            回乡证(5,"港澳通行证"),*/
        switch (Number(idType)) {
            case 1:
                return "身份证";
            case 2:
                return "永居证";
            case 3:
                return "台胞证";
            case 4:
                return "护照";
            case 5:
                return "港澳通行证";
        }
    };

    const transferWeekDay = (date:string) => {
        const today = dayjs().startOf('day');
        const target = dayjs(date).startOf('day');

        if (!target.isValid()) return '无效日期';

        const diff = target.diff(today, 'day');
        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];

        switch (diff) {
            case 0: return '今天';
            case 1: return '明天';
            case 2: return '后天';
            default: return weekdays[target.day()];
        }
    };

    const calculateAge = (idCard, currentDate) => {
        if (idCard.length !== 18) {
            throw new Error("身份证号码必须为18位");
        }

        const birthDateStr = idCard.substring(6, 14);

        // 解析出生年月日
        const birthYear = parseInt(birthDateStr.substring(0, 4), 10);
        const birthMonth = parseInt(birthDateStr.substring(4, 6), 10);
        const birthDay = parseInt(birthDateStr.substring(6, 8), 10);

        // 验证出生日期有效性
        const birthDate = new Date(birthYear, birthMonth - 1, birthDay);
        if (
            birthDate.getFullYear() !== birthYear ||
            birthDate.getMonth() + 1 !== birthMonth ||
            birthDate.getDate() !== birthDay
        ) {
            throw new Error("身份证中的出生日期无效");
        }

        // 解析当前日期
        const currentParts = currentDate.split("-");
        if (currentParts.length !== 3) {
            throw new Error("当前日期格式应为YYYY-MM-DD");
        }

        const currentYear = parseInt(currentParts[0], 10);
        const currentMonth = parseInt(currentParts[1], 10);
        const currentDay = parseInt(currentParts[2], 10);

        // 验证当前日期有效性
        const currentDateObj = new Date(currentYear, currentMonth - 1, currentDay);
        if (
            currentDateObj.getFullYear() !== currentYear ||
            currentDateObj.getMonth() + 1 !== currentMonth ||
            currentDateObj.getDate() !== currentDay
        ) {
            throw new Error("当前日期无效");
        }

        // 计算年龄
        let age = currentYear - birthYear;

        // 判断是否已过生日
        if (currentMonth < birthMonth) {
            age--;
        } else if (currentMonth === birthMonth && currentDay < birthDay) {
            age--;
        }

        return age;
    }
    const convertGender = (idCard) => {
        if (idCard.length !== 18) {
            throw new Error("身份证号码必须为18位");
        }
        const genderCode = idCard.charAt(16);
        if (!/^\d$/.test(genderCode)) {
            throw new Error("身份证号码第17位应为数字");
        }
        return parseInt(genderCode, 10) % 2 === 1 ? 1 : 2;
    };
    const dynamicGrouping = (data,number) => {
        if (number <= 0) return "分组数必须大于0";
        const groups = [];
        for (let j = 0; j < number; j++) {
            groups.push([]);
        }
        for (let k = 0; k < data.length; k++) {
            const groupIndex = k % number;
            groups[groupIndex].push(data[k]);
        }
        return groups;
    };
    const handleNavToProviderDetail = (event: ProviderDetailEvent) => {
        /*
        * type 服务商类型
        * 0 景区
        * 1 酒店
        * 2 交通
        * 3 商城
        * 4 餐厅
        * 5 旅行社
        * */
        let { type,id,name } = event;
        let path: string = "";
        switch (Number(type)) {
            case 0:
                path = `/ticketSubPack/pages/scenicSpotDetail/index?id=${id}&name=${name}`;
                break;
            case 1:
                if(!hotelStore.getbeginDate || !hotelStore.getendDate) {
                    hotelStore.setbeginDate(dayjs().format("YYYY-MM-DD"));
                    hotelStore.setendDate(dayjs().add(1, 'day').format('YYYY-MM-DD'))
                }
                path = `/hotelHomestay/pages/hotelDteail/index?id=${id}`;
                break;
            case 2:
                path = "";
                break;
            case 3:
                path = `/specialtySubPack/pages/specialtyProvider/index?productId=${id}&providerName=${name}`;
                break;
            case 4:
                path = `/foodSubPack/pages/foodProviderDetail/index?providerId=${id}`;
                break;
            case 5:
                path = `/premiumRouteSubPack/pages/merchant/index?id=${id}&merchantId=${id}`;
                break;
        }
        if(path) {
            uni.navigateTo({
                url: path
            })
        }

    };
    return {
        pageBack,
        distanceTransform,
        providerStatus,
        transferIdCardType,
        transferWeekDay,
        calculateAge,
        convertGender,
        dynamicGrouping,
        handleNavToProviderDetail
    };
}
